package com.fyt.ZhongYaoApp.service.impl;


import com.fyt.ZhongYaoApp.mapper.AddressBookMapper;
import com.fyt.ZhongYaoApp.pojo.AddressBook;
import com.fyt.ZhongYaoApp.pojo.User;
import com.fyt.ZhongYaoApp.service.AddressBookService;
import com.fyt.ZhongYaoApp.service.UserService;
import com.fyt.ZhongYaoApp.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserService userService;

    /**
     * 条件查询
     *
     * @param addressBook
     * @return
     */
    public List<AddressBook> list(AddressBook addressBook) {
        return addressBookMapper.list(addressBook);
    }

    /**
     * 新增地址
//     *
//     * @param addressBook
//     */
    public void save(AddressBook addressBook) {
        Integer userId;
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUserName(username);
        userId = user.getId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    public void update(AddressBook addressBook) {

        addressBookMapper.update(addressBook);

    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Transactional
    public void setDefault(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址
        // update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        //2、获取用户id
        Integer userId;
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUserName(username);
        userId = user.getId();
        addressBook.setUserId(userId);
        //3、将当前所有地址改为非默认
//        System.out.println(addressBook);
        addressBookMapper.updateIsDefaultByUserId(addressBook);
        System.out.println(addressBook);

        //4、将当前地址改为默认地址
        // update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

}
